// pages/question-detail/question-detail.js
const app = getApp()

Page({
  // 难度等级映射
  getDifficultyClass(difficulty) {
    const difficultyMap = {
      '简单': 'easy',
      '中等': 'medium', 
      '困难': 'hard',
      'easy': 'easy',
      'medium': 'medium',
      'hard': 'hard'
    }
    return difficultyMap[difficulty] || 'medium'
  },
  data: {
    question: null,
    bankId: null,
    questionId: null,
    bankName: '',
    currentIndex: 0,
    totalCount: 0,
    bankQuestions: [],
    // 收藏状态
    isFavorited: false,
    // 答题状态
    selectedAnswers: [], // 选择题答案
    fillAnswer: '', // 填空题答案
    judgeAnswer: null, // 判断题答案 true/false
    isSubmitted: false, // 是否已提交
    showAnalysis: false, // 是否显示解析
    isCorrect: false // 答案是否正确
  },

  onLoad(options) {
    const { bankId, questionId } = options
    this.setData({
      bankId,
      questionId
    })
    this.loadQuestion()
  },

  loadQuestion() {
    const { bankId, questionId } = this.data
    const questionBanks = app.globalData.questionBanks
    
    // 找到对应题库
    const bank = questionBanks.find(b => b.id === parseInt(bankId))
    if (!bank) return
    
    // 找到题库中的题目
    const bankQuestions = app.globalData.questionBank.filter(q => 
      bank.questionIds.includes(q.id)
    )
    
    // 找到当前题目
    const question = bankQuestions.find(q => q.id === parseInt(questionId))
    const currentIndex = bankQuestions.findIndex(q => q.id === parseInt(questionId))
    
    // 检查收藏状态
    const favorites = wx.getStorageSync('favorites') || []
    const isFavorited = favorites.includes(parseInt(questionId))
    
    // 为选项添加选中状态
    if (question && question.options) {
      question.options = question.options.map((option, index) => ({
        ...option,
        selected: false,
        index: index
      }))
    }
    
    this.setData({
      question,
      bankName: bank.name,
      currentIndex,
      totalCount: bankQuestions.length,
      bankQuestions,
      isFavorited,
      // 重置答题状态
      selectedAnswers: [],
      fillAnswer: '',
      judgeAnswer: null,
      isSubmitted: false,
      showAnalysis: false,
      isCorrect: false
    })
  },

  // 切换收藏状态
  toggleFavorite() {
    const { questionId, isFavorited } = this.data
    let favorites = wx.getStorageSync('favorites') || []
    
    if (isFavorited) {
      // 取消收藏
      favorites = favorites.filter(id => id !== parseInt(questionId))
      wx.showToast({
        title: '已取消收藏',
        icon: 'success'
      })
    } else {
      // 添加收藏
      favorites.push(parseInt(questionId))
      wx.showToast({
        title: '收藏成功',
        icon: 'success'
      })
    }
    
    wx.setStorageSync('favorites', favorites)
    this.setData({
      isFavorited: !isFavorited
    })
  },

  // 选择题选项点击
  onOptionSelect(e) {
    const index = parseInt(e.currentTarget.dataset.index)
    const { question, selectedAnswers } = this.data
    
    // 更新选项的选中状态
    const updatedOptions = question.options.map((option, i) => {
      if (question.type === 'single') {
        // 单选题：只有当前选项被选中
        return { ...option, selected: i === index }
      } else if (question.type === 'multiple') {
        // 多选题：切换当前选项的选中状态
        if (i === index) {
          return { ...option, selected: !option.selected }
        }
        return option
      }
      return option
    })
    
    // 更新selectedAnswers数组
    let newSelectedAnswers = []
    if (question.type === 'single') {
      newSelectedAnswers = [index]
    } else if (question.type === 'multiple') {
      newSelectedAnswers = updatedOptions
        .map((option, i) => option.selected ? i : null)
        .filter(i => i !== null)
    }
    
    this.setData({
      question: { ...question, options: updatedOptions },
      selectedAnswers: newSelectedAnswers
    })
  },

  // 填空题输入
  onFillInput(e) {
    this.setData({
      fillAnswer: e.detail.value
    })
  },

  // 判断题选择
  onJudgeSelect(e) {
    const { value } = e.currentTarget.dataset
    this.setData({
      judgeAnswer: value === 'true'
    })
  },

  // 提交答案
  submitAnswer() {
    const { question, selectedAnswers, fillAnswer, judgeAnswer } = this.data
    let userAnswer = null
    let isCorrect = false
    
    // 根据题型获取用户答案
    switch (question.type) {
      case 'single':
        if (selectedAnswers.length === 0) {
          wx.showToast({
            title: '请选择答案',
            icon: 'none'
          })
          return
        }
        userAnswer = selectedAnswers[0]
        isCorrect = userAnswer === question.correctAnswer
        break
        
      case 'multiple':
        if (selectedAnswers.length === 0) {
          wx.showToast({
            title: '请选择答案',
            icon: 'none'
          })
          return
        }
        userAnswer = selectedAnswers.sort()
        isCorrect = JSON.stringify(userAnswer) === JSON.stringify(question.correctAnswer.sort())
        break
        
      case 'fill':
        if (!fillAnswer.trim()) {
          wx.showToast({
            title: '请输入答案',
            icon: 'none'
          })
          return
        }
        userAnswer = fillAnswer.trim()
        isCorrect = userAnswer === question.correctAnswer
        break
        
      case 'judge':
        if (judgeAnswer === null) {
          wx.showToast({
            title: '请选择答案',
            icon: 'none'
          })
          return
        }
        userAnswer = judgeAnswer
        isCorrect = userAnswer === question.correctAnswer
        break
    }
    
    // 记录答题历史
    this.recordAnswer(userAnswer, isCorrect)
    
    this.setData({
      isSubmitted: true,
      showAnalysis: true,
      isCorrect
    })
    
    wx.showToast({
      title: isCorrect ? '回答正确！' : '回答错误',
      icon: isCorrect ? 'success' : 'none'
    })
  },

  // 记录答题历史
  recordAnswer(userAnswer, isCorrect) {
    const { questionId, question, bankName } = this.data
    let history = wx.getStorageSync('answerHistory') || []
    
    // 移除已存在的记录
    history = history.filter(item => item.questionId !== parseInt(questionId))
    
    // 添加新记录，包含完整题目信息
    history.unshift({
      id: Date.now(), // 唯一ID用于删除操作
      questionId: parseInt(questionId),
      title: question.title,
      type: question.type,
      bankName: bankName,
      userAnswer,
      correctAnswer: question.correctAnswer,
      isCorrect,
      timestamp: Date.now(),
      dateString: this.formatDate(new Date())
    })
    
    // 只保留最近100条记录
    if (history.length > 100) {
      history = history.slice(0, 100)
    }
    
    wx.setStorageSync('answerHistory', history)
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}`
  },

  // 上一题
  prevQuestion() {
    const { currentIndex, bankQuestions } = this.data
    if (currentIndex > 0) {
      const prevQuestion = bankQuestions[currentIndex - 1]
      wx.redirectTo({
        url: `/pages/question-detail/question-detail?bankId=${this.data.bankId}&questionId=${prevQuestion.id}`
      })
    } else {
      wx.showToast({
        title: '已经是第一题了',
        icon: 'none'
      })
    }
  },

  // 下一题
  nextQuestion() {
    const { currentIndex, bankQuestions } = this.data
    if (currentIndex < bankQuestions.length - 1) {
      const nextQuestion = bankQuestions[currentIndex + 1]
      wx.redirectTo({
        url: `/pages/question-detail/question-detail?bankId=${this.data.bankId}&questionId=${nextQuestion.id}`
      })
    } else {
      wx.showToast({
        title: '已经是最后一题了',
        icon: 'none'
      })
    }
  },

  // 返回题库详情
  goBackToBank() {
    wx.navigateBack()
  }
})